const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch({
    executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',   //指定chromium浏览器位置;
    headless: false,  //默认为true 表示不打开浏览器展示;
    timeout: 100000     //超时操作 默认为30s 1000ms=1s;
  });
  const page = await browser.newPage();
  await page.goto('https://pvp.qq.com/web201605/wallpaper.shtml');
  // 获取视图宽高
  // const documentSize = await page.evaluate(() => {
  //   return {
  //     width: document.documentElement.clientWidth,
  //     height: document.body.clientHeight
  //   }
  // })
  // await setInterval(() => {
  //   //截屏
  //   let now = new Date()
  //   let pngName = now.getSeconds()
  //   page.screenshot({
  //     path: `图${pngName}.png`,
  //     clip: {
  //       x: 0,
  //       y: 0,
  //       width: documentSize.width,
  //       height: documentSize.height
  //     }
  //   });
  // }, 50000)


  // $$('ul > li.sProdImgDown.sProdImgL7 > a').map(x=>x.href)
  // $$('h4 > a').map(x=>x.innerText)
  //找节点

  const _Img = 'ul > li.sProdImgDown.sProdImgL7 > a'
  await page.waitForSelector(_Img)
  const _Title = 'h4 > a '
  await page.waitForSelector(_Title)
  // const ex = await page.$$(Img)
  // 获取内容
  const Title = await page.$$eval(_Title, el => el.map(x => x.innerText));
  const Img = await page.$$eval(_Img, el => el.map(x => x.href));
  let arr = []
  for (let i = 0; i < Title.length; i++) {
    arr.push({
      "title": Title[i],
      "img-url": Img[i]
    })
  }
  //写入JSON
  fs.appendFile('data.json', JSON.stringify(arr,null,"\t"), (err) => {
    if (err) throw err;
    console.log('该文件已创建!');
  });
  //等待
  await page.waitFor(3000)
  // 关闭浏览器
  // await browser.close();
})();